package router

import (
	"errors"
	"iris-wms/apps/admin/web/dto/din"
	"iris-wms/apps/admin/web/service"
	"iris-wms/common/tools"
	"iris-wms/common/tools/consts"
	"iris-wms/common/tools/result"

	"github.com/kataras/iris/v12"
)

func NewWmsBillInboundRoute() *wmsBillInboundRoute {
	return &wmsBillInboundRoute{}
}

type wmsBillInboundRoute struct{}

func (r *wmsBillInboundRoute) Create(ctx iris.Context, service_ service.WmsBillService) {
	var in din.WmsBillIn
	if err := ctx.ReadJSON(&in); err != nil {
		ctx.StopWithPlainError(iris.StatusBadRequest, err)
		return
	}
	in.Bill.Uid = tools.GetUserID(ctx)
	in.Bill.WorkType = consts.WorkType1
	if err := service_.Create(in, consts.BillMarkIn); err != nil {
		if errors.Is(err, consts.Wms_Bill_Not_Goods) {
			ctx.StopWithPlainError(iris.StatusBadRequest, err)
			return
		}
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	result.OK(ctx)
}

func (r *wmsBillInboundRoute) Edit(ctx iris.Context, service_ service.WmsBillService) {
	var in din.WmsBillIn
	if err := ctx.ReadJSON(&in); err != nil {
		ctx.StopWithPlainError(iris.StatusBadRequest, err)
		return
	}
	in.Bill.Euid = tools.GetUserID(ctx)
	in.Bill.WorkType = consts.WorkType1
	if err := service_.Update(in, consts.BillMarkIn); err != nil {
		if errors.Is(err, consts.Wms_Bill_Not_Goods) {
			ctx.StopWithPlainError(iris.StatusBadRequest, err)
			return
		}
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	result.OK(ctx)
}

func (r *wmsBillInboundRoute) Delete(ctx iris.Context, service_ service.WmsBillService) {
	var idList = make([]uint, 0)
	if err := ctx.ReadJSON(&idList); err != nil {
		ctx.StopWithPlainError(iris.StatusBadRequest, err)
		return
	}
	if err := service_.DeleteByIdList(idList); err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	result.OK(ctx)
}

func (r *wmsBillInboundRoute) Table(ctx iris.Context, service_ service.WmsBillService) {
	var in din.WmsBillTableIn
	if err := ctx.ReadQuery(&in); err != nil {
		ctx.StopWithPlainError(iris.StatusBadRequest, err)
		return
	}
	in.WorkType = consts.WorkType1
	rows, total, err := service_.GetTable(in)
	if err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	result.VxeTableData(ctx, in.PageSize, in.CurrentPage, total, rows, nil)
}

func (r *wmsBillInboundRoute) GetByCode(ctx iris.Context, service_ service.WmsBillService) {
	var code = ctx.URLParamDefault("code", "")
	if code == "" {
		ctx.StopWithPlainError(iris.StatusBadRequest, errors.New("查询单据的code为空"))
		return
	}
	one, err := service_.FindByCode(code, consts.WorkType1)
	if err != nil {
		ctx.StopWithPlainError(iris.StatusInternalServerError, err)
		return
	}
	result.OKData(ctx, one)
}
